package thread;

import lombok.AllArgsConstructor;
import lombok.Getter;

import java.util.Arrays;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 生产者和消费者多线程
 * @author ZhouJie
 * @date 2021-11-06 16:17
 */
public class ProducerAndConsumerTest {

    public static void main(String[] args) {
        Factory factory = new Factory(50);

        for (String s : Arrays.asList("消费者ONE","消费者TWO")){
           new Thread(()->{
               while (true) {
                   factory.consumer();
               }
           },s).start();
       }

        for (String s: Arrays.asList("生产者ONE","生产者TWO")){
            new Thread(()->{
                while (true) factory.product();
            },s).start();
        }
    }


}

@Getter
@AllArgsConstructor
class Factory{
    private int num;

    private final Lock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();

    public  void product(){
        lock.lock();
        try {
            if (num >=20){
                //wait();
                condition.await();
            } else{
                num ++;
                System.out.println(Thread.currentThread().getName()+":生产了一个数量,余："+num);
                //notify();
                condition.signal();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }

    public void consumer(){
        lock.lock();
        try {
            if (num <= 0){
                //wait();
                condition.await();
            }else{
                num --;
                System.out.println(Thread.currentThread().getName()+":消费掉了一个数量,余："+num);
                condition.signal();
            }
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
